#coding:utf-8
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.core.serializers.json import DjangoJSONEncoder
from users.models import Info
from groups.models import Topic
from courses.models import Course
from rewards.models import Reward
import sphinxapi
import json


def index(request):
    #index = ''
    #keyword = ''
    #读session
    try:
        user_id = request.session['id']
    except KeyError:
        return HttpResponseRedirect(reverse('login:index'))
    #index source dict
    index_source = ('*', 'user', 'topic', 'course', 'reward')
    if request.method == 'POST':
        index = request.POST.get('index', '')
        keyword = request.POST.get('keyword', '')
        if index == '':
            index = 1
        index = int(index)
        error = ''
        result = None
        #查询
        try:
            #创建sphinx客户端
            sphinx = sphinxapi.SphinxClient()
            sphinx.SetMatchMode(sphinxapi.SPH_MATCH_ALL)
            result = sphinx.Query(keyword, index_source[index])
            #检查错误和警告
            error = sphinx.GetLastError()
            #warning = sphinx.GetLastWarning()
        except StandardError as e:
            print e.message
        #若没有错误警告
        if error == '':
            #搜索
            response = None
            if index == 1:
                #人
                response = search_user(result)
            elif index == 2:
                #话题
                response = search_topic(result)
            elif index == 3:
                #课程
                response = search_course(result)
            elif index == 4:
                #悬赏
                response = search_reward(result)
            return response
        else:
            #错误存在
            data = {}
            data['error'] = error
            print(data)
            return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        #不是提交Post请求
        return render(request, 'search/index.html', {'user_id': user_id})


def search_user(matches):
    #搜索用户
    data = {}
    users = []
    for match in matches['matches']:
        try:
            info = Info.objects.get(id=match['id'])
            users.append({'id': str(info.id), 'user_name': info.user_name})
        except ObjectDoesNotExist:
            pass
    #匹配数，用户数据
    data['total'] = matches['total_found']
    data['users'] = users
    data['error'] = ''
    print(data)
    return HttpResponse(json.dumps(data), content_type='application/json')



def search_topic(matches):
    #搜索话题
    data = {}
    topics = []
    for match in matches['matches']:
        try:
            topic = Topic.objects.get(id=match['id'])
            topics.append({'id': str(topic.id), 'name': topic.name, 'content': topic.content, 'time': topic.last_time})
        except ObjectDoesNotExist:
            pass
    #匹配数，用户数据
    data['total'] = matches['total_found']
    data['topics'] = topics
    data['error'] = ''
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type='application/json')


def search_course(matches):
    #搜索课程
    data = {}
    courses = []
    for match in matches['matches']:
        try:
            course = Course.objects.get(id=match['id'])
            courses.append({'id': str(course.id), 'name': course.name, 'introduce': course.introduce, 'time': course.time})
        except ObjectDoesNotExist:
            pass
    #匹配数，用户数据
    data['total'] = matches['total_found']
    data['courses'] = courses
    data['error'] = ''
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type='application/json')


def search_reward(matches):
    #搜索悬赏
    data = {}
    rewards = []
    for match in matches['matches']:
        try:
            reward = Reward.objects.get(id=match['id'])
            rewards.append({'id': str(reward.id), 'name': reward.name, 'introduce': reward.introduce, 'time': reward.time})
        except ObjectDoesNotExist:
            pass
    #匹配数，用户数据
    data['total'] = matches['total_found']
    data['rewards'] = rewards
    data['error'] = ''
    print(data)
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type='application/json')